﻿using System;
using System.ComponentModel.Composition;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Unity;
using Silverlight.Weblog.Client.DAL.Events;
using Silverlight.Weblog.Client.DAL.Services.Interfaces;
using Silverlight.Weblog.Common.IoC;
using System.Linq;
using Silverlight.Weblog.Server.DAL;

namespace Silverlight.Weblog.Client.DAL.Services
{
    public class GoToBlogPostService : IGoToBlogPostService
    {
        [Dependency]
        public IDBContextContainer DBContextContainer { get; set; }

        public void NavigateToBlogPostPermlinkEvent(string permlink)
        {
            BlogPost LocalBlogPost = DBContextContainer.Current.Users
                                                               .Select(u => u.Posts
                                                                             .FirstOrDefault(p => p.Permlink == permlink))
                                                               .FirstOrDefault();

            if (LocalBlogPost != null)
                GoTo(LocalBlogPost);
            else
            {
                DBContextContainer.Current
                    .Load(DBContextContainer.Current.GetBlogPostByPermlinkQuery(permlink),
                          initial =>GoTo(initial.Entities.First())
                          , null);
            }
        }

        public void GoTo(BlogPost blogPost)
        {
            IoC.Get<IEventAggregator>().GetEvent<GoToBlogPostEvent>().Publish(blogPost);
            IoC.Get<IEventAggregator>().GetEvent<ChangingTitleEvent>().Publish(string.Empty);
        }
    }
}
